package com.blog.support.config;

import com.alibaba.fastjson.JSON;
import org.apache.catalina.filters.RemoteIpFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * web过滤连接
 */
@Configuration
public class WebConfig {

    private final static Logger logger = LoggerFactory.getLogger(WebConfig.class);

    /**
     * 将代理服务器发来的请求包含的IP地址转换成真正的用户IP
     * @return
     */
    @Bean
    public RemoteIpFilter remoteIpFilter(){
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean urlFilterRegistration(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new UrlFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter("paramName", "paramValue");
        registrationBean.setName("UrlFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    public class UrlFilter implements Filter {
        @Override
        public void destroy() {
        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) srequest;
            logger.info("url : {}", request.getRequestURI());
            Enumeration<String> enumeration = request.getParameterNames();
            Map<String, Object> params = new HashMap<>();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                Object name = request.getParameter(key);
                params.put(key, name);
            }
            logger.info("prams : {}" , JSON.toJSONString(params));
            filterChain.doFilter(srequest, sresponse);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }

}
